package DBCPUtil;

import org.apache.commons.dbcp2.BasicDataSource;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;
import java.io.FileReader;
import java.io.Reader;
import java.util.Properties;

@WebListener
public class DBCPUtil implements ServletContextListener {
    //创建连接池对象
    private static  BasicDataSource basicDataSource = new BasicDataSource();
     public void contextInitialized(ServletContextEvent sce) {
         try {
             //properties集合
             Properties properties = new Properties();
             String path = sce.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
             //读取配置文件
             //输入流将文件内容读取到内存中
             Reader reader=new FileReader(path);
             //将内存中的信息加载到properties集合中
             properties.load(reader);
             //设置连接池对象相关属性
             basicDataSource.setDriverClassName(properties.getProperty("jdbc.driver"));
             basicDataSource.setUrl(properties.getProperty("jdbc.url"));
             basicDataSource.setUsername(properties.getProperty("jdbc.user"));
             basicDataSource.setPassword(properties.getProperty("jdbc.password"));
         }catch (Exception e){
             System.out.println("文件未找到"+e.toString());
         }
     }
    //在静态代码块中给连接池对象设置相关属性

    /*
    * 将连接池对象返回
    * */
    public static DataSource getDataSource(){
        return basicDataSource;
    }
}
